package com.zlx.sharelive.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.CommentBean;
import com.zlx.module_base.base_api.res_data.VideoCommentListBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.TimeUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 评论
 */
public class ReviewFg extends BaseFg {

    @BindView(R.id.rv_data)
    RecyclerView rv_data;
    @BindView(R.id.et_text)
    EditText et_text;
    @BindView(R.id.tv_comm)
    TextView tv_comm;
    @BindView(R.id.sw_layout)
    SwipeRefreshLayout sw_layout;
    @BindView(R.id.tv_entire)
    TextView tv_entire;
    @BindView(R.id.tv_latest)
    TextView tv_latest;
    @BindView(R.id.tv_hottest)
    TextView tv_hottest;

    private String type = "1";
    private String pid = "-1";
    private String id = "";
    private List<TextView> mTextViewList = new ArrayList<>();
    private List<VideoCommentListBean.InfoDTO> mList = new ArrayList<>();
    private List<VideoCommentListBean.InfoDTO> mList2 = new ArrayList<>();
    private CommonRecyclerViewAdapter<VideoCommentListBean.InfoDTO> mAdapter;

    public static ReviewFg getInstance(String id) {
        ReviewFg reviewFg = new ReviewFg();
        Bundle bundle = new Bundle();
        bundle.putSerializable("id", id);
        reviewFg.setArguments(bundle);
        return reviewFg;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fg_review;
    }


    @Override
    protected void initViews() {
        super.initViews();

        id = getArguments().getString("id");
        mTextViewList.clear();
        mTextViewList.add(tv_entire);
        mTextViewList.add(tv_latest);
        mTextViewList.add(tv_hottest);

        getVideoCommentList();
        initRecyclerView();

        sw_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                id = getArguments().getString("id");
                getVideoCommentList();
            }
        });
    }

    /**
     * 获取长视频评论
     */
    private void getVideoCommentList() {
        ApiUtil.getVideoApi().getVideoCommentList(SPUtil.getToken(getContext()),
                id, type).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoCommentListBean>>() {
            @Override
            public void onSuccess(ApiResponse<VideoCommentListBean> data) {
                sw_layout.setRefreshing(false);
                mList.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (null != data.getData().getInfo()) {
                            mList.addAll(data.getData().getInfo());
                        }
                    }
                }
                mList2.clear();
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getPid().equals("-1")) {
                        mList2.add(mList.get(i));
                    }
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                sw_layout.setRefreshing(false);
            }
        }));
    }


    /**
     * 初始化数据
     */
    private void initRecyclerView() {
        rv_data.setLayoutManager(new LinearLayoutManager(getContext()));

        rv_data.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //解决mRecyclerView与mSwipeRefreshLayout在部分机型上滑动冲突
                sw_layout.setEnabled(recyclerView.getChildCount() == 0 || recyclerView.getChildAt(0).getTop() >= 0);
            }
        });

        mAdapter = new CommonRecyclerViewAdapter<VideoCommentListBean.InfoDTO>(getContext(), mList2) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, VideoCommentListBean.InfoDTO entity, int position) {
                ImageView iv_review_head = holder.getView(R.id.iv_review_head);
                GlideImgManager.glideLoader(getContext(), entity.getAvatar(), iv_review_head, 0);
                holder.setText(R.id.tv_review_nickname, entity.getNickname());
                holder.setText(R.id.tv_review_text, entity.getComment());
                try {
                    holder.setText(R.id.tv_time, TimeUtil.getTimeStringAutoShort2(TimeUtil.ConverToDate(entity.getCreateTime()), true));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                RecyclerView rv_review = holder.getView(R.id.rv_review);
                rv_review.setLayoutManager(new LinearLayoutManager(getContext()));


                rv_review.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);
                        //解决mRecyclerView与mSwipeRefreshLayout在部分机型上滑动冲突
                        sw_layout.setEnabled(recyclerView.getChildCount() == 0 || recyclerView.getChildAt(0).getTop() >= 0);
                    }
                });

                List<VideoCommentListBean.InfoDTO> newList = new ArrayList<>();
                newList.clear();
                //1级评论数据
                for (int i = 0; i < mList.size(); i++) {
                    if (!StringUt.isEmpty(mList.get(i).getPid())) {
                        if (!mList.get(i).getPid().equals("-1")) {
                            if (mList.get(i).getPid().equals(entity.getId())) {
                                newList.add(mList.get(i));
                            }
                        }
                    }
                }
                //2级评论数据
                for (int i = 0; i < mList.size(); i++) {
                    if (!StringUt.isEmpty(mList.get(i).getPid())) {
                        for (int j = 0; j < newList.size(); j++) {
                            if (!StringUt.isEmpty(newList.get(j).getPid())) {
                                if (mList.get(i).getPid().equals(newList.get(j).getId())) {
                                    newList.add(mList.get(i));
                                }
                            }
                        }
                    }
                }
                //2级评论的回复
                for (int i = 0; i < newList.size(); i++) {
                    for (int j = 0; j < newList.size(); j++) {
                        if (newList.get(i).getPid().equals(newList.get(j).getId())) {
                            newList.get(i).setFlag(true);
                            newList.get(i).setName(newList.get(j).getNickname());
                        }
                    }
                }

                CommonRecyclerViewAdapter<VideoCommentListBean.InfoDTO> adapter = new CommonRecyclerViewAdapter<VideoCommentListBean.InfoDTO>(getContext(), newList) {
                    @Override
                    public void convert(CommonRecyclerViewHolder holder, VideoCommentListBean.InfoDTO entity, int position) {
                        ImageView iv_review_head = holder.getView(R.id.iv_review_head);
                        GlideImgManager.glideLoader(getContext(), entity.getAvatar(), iv_review_head, 0);
                        holder.setText(R.id.tv_review_nickname, entity.getNickname());
                        holder.setText(R.id.tv_review_text, entity.getComment());
                        if (entity.isFlag() == true) {
                            ((LinearLayout) holder.getView(R.id.ll_reply)).setVisibility(View.VISIBLE);
                            holder.setText(R.id.tv_nickname2, entity.getName());
                        } else {
                            ((LinearLayout) holder.getView(R.id.ll_reply)).setVisibility(View.GONE);
                        }

                        try {
                            holder.setText(R.id.tv_time, TimeUtil.getTimeStringAutoShort2(TimeUtil.ConverToDate(entity.getCreateTime()), true));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public int getLayoutViewId(int viewType) {
                        return R.layout.item_review2;
                    }
                };

                rv_review.setAdapter(adapter);

                adapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        et_text.setHint("@" + newList.get(position).getNickname());
                        pid = newList.get(position).getId();
                    }
                });
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_review;
            }
        };

        rv_data.setAdapter(mAdapter);

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                et_text.setHint("@" + mList2.get(position).getNickname());
                pid = mList2.get(position).getId();
            }
        });
    }


    @OnClick({R.id.tv_comm, R.id.tv_entire, R.id.tv_latest, R.id.tv_hottest})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_comm:
                if (StringUt.isEmpty(et_text.getText().toString().trim())) {
                    Toast.makeText(getContext(), "内容不可为空", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    addComment();
                }
                break;
            case R.id.tv_entire:
                setTextViewColor(0);
                type = "1";
                getVideoCommentList();
                break;
            case R.id.tv_latest:
                setTextViewColor(1);
                type = "1";
                getVideoCommentList();
                break;
            case R.id.tv_hottest:
                setTextViewColor(2);
                type = "2";
                getVideoCommentList();
                break;
        }
    }

    /**
     * 新增视频评论
     */
    private void addComment() {
        CommentBean commentBean = new CommentBean();
        commentBean.setPid(pid);
        commentBean.setUid((String) SPUtil.get(getContext(), Constants.SP_ID, ""));
        commentBean.setVid(id);
        commentBean.setComment(et_text.getText().toString().trim());

        ApiUtil.getVideoApi().addComment(SPUtil.getToken(getContext()),
                commentBean
        ).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                if (null != data) {
                    if (data.getData().getCode() == 0) {
                        pid = "-1";
                        et_text.setText("");
                        et_text.setHint("发表评论，分享自己的看法");
                        id = getArguments().getString("id");
                        getVideoCommentList();
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    public void setTextViewColor(int position) {
        for (int i = 0; i < mTextViewList.size(); i++) {
            if (i == position) {
                mTextViewList.get(i).setTextColor(getResources().getColor(R.color.hot_pink));
                mTextViewList.get(i).setBackgroundResource(R.drawable.edit_bg_pale_rose);
            } else {
                mTextViewList.get(i).setTextColor(getResources().getColor(R.color.martini));
                mTextViewList.get(i).setBackgroundResource(R.drawable.edit_bg_gallery);
            }
        }
    }
}
